package pers.brozen.anka.service;

import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import pers.brozen.anka.apis.params.WechatMiniProgramLoginParam;
import pers.brozen.anka.dao.entity.AnkaSession;
import pers.brozen.anka.dao.entity.WechatUser;
import pers.brozen.anka.dao.repository.WechatUserRepository;
import pers.brozen.anka.service.ac.WechatMiniProgramAC;
import pers.brozen.anka.support.wechat.response.MiniProgramCode2SessionResult;

/**
 * @author Brozen
 * @since 2024-05-28
 */
@Service
public class WechatAuthService {

    @Resource
    private SessionService sessionService;

    @Resource
    private WechatMiniProgramAC wechatMiniProgramAC;

    @Resource
    private WechatUserRepository wechatUserRepo;


    public AnkaSession login(WechatMiniProgramLoginParam param) {
        MiniProgramCode2SessionResult wxSession =
                wechatMiniProgramAC.requestWeChatSession(param.getCode());
        String openId = wxSession.getOpenid();

        WechatUser user = wechatUserRepo.getByMiniProgramOpenId(openId);
        if (user == null) {
            user = new WechatUser();
        }
        user.updateWechatMiniProgramSession(wxSession);

        // 创建用户信息
        wechatUserRepo.save(user);

        // 生成会话
        return sessionService.createWechatMiniProgramSession(user);
    }

}
